package com.gitee.cui.petstore.actor;

import com.gitee.cui.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 通用消费者类
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/19 14:13
 **/
@Slf4j
public class Consumer implements Runnable {

    /**
     * 消费时间间隔
     */
    private static final int CONSUMER_GAP = 100;

    /**
     * 消费总次数
     */
    private static final AtomicInteger TURN = new AtomicInteger(0);

    /**
     * 消费者编号
     */
    private static final AtomicInteger CONSUMER_NO = new AtomicInteger(0);

    /**
     * 消费者名称
     */
    private String name;

    /**
     * 消费者动作执行类
     */
    private Callable<?> action;

    /**
     * 消费者动作执行间隔
     */
    private int gap = CONSUMER_GAP;

    public Consumer(Callable<?> action, int gap) {
        this.action = action;
        this.gap = gap;
        this.name = "消费者-" + CONSUMER_NO.incrementAndGet();
    }

    @Override
    public void run() {
        while (true) {
            // 增加消费次数
            TURN.incrementAndGet();
            try {
                // 执行消费动作
                Object result = action.call();
                if (result != null) {
                    log.info("第{}轮消费：{}", TURN.get(), result);
                }
                ThreadUtil.sleepMilliSeconds(gap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
